@page "/ConditionalFormatting"
@using Region = BlazorDatasheet.DataStructures.Geometry.Region
@using BlazorDatasheet.Core.Data
@using BlazorDatasheet.Core.Formats
@using BlazorDatasheet.Core.Formats.DefaultConditionalFormats
@using System.Drawing
<PageTitle>Conditional Formatting</PageTitle>

<h1>Conditional Formatting</h1>

<p>
    This example shows two conditional formats applied to the cells in the sheet

    <ol>
        <li>Column 1: Shows a "check" icon if the cell contains the word check.</li>
        <li>Columns 2 - 6: Shows a colour gradient that depends on the cell's value in relation to all others with the conditional format applied.</li>
    </ol>
</p>

<div>
    <Datasheet
        Icons="iconDictionary"
        Sheet="sheet">
    </Datasheet>
</div>

@code {

    private Sheet sheet;

    private Dictionary<string, RenderFragment> iconDictionary = new()
    {
        {
            "check",
            Icons.Icons.CheckIcon
        }
    };

    protected override void OnInitialized()
    {
        sheet = new Sheet(15, 5);
        var numberScaleConditionalFormat = new NumberScaleConditionalFormat(Color.YellowGreen, Color.IndianRed);
        var checkConditionalFormat = new CustomCheckConditionalFormat("check");

        var values = new List<(int row, int col, object value)>();

        var regionOfNumberScaleFormat = new Region(0, sheet.NumRows-1, 1, sheet.NumRows-1);
        var rand = new Random();
        foreach (var posn in regionOfNumberScaleFormat)
        {
            values.Add((posn.row, posn.col, (int?)rand.Next(100)));
        }

        sheet.Cells.SetValues(values);

        sheet.ConditionalFormats.Apply(new Region(0, 99, 1, 4), numberScaleConditionalFormat);
        sheet.ConditionalFormats.Apply(new Region(0, 99, 0, 0), checkConditionalFormat);

        base.OnInitialized();
    }

    public class CustomCheckConditionalFormat : ConditionalFormatAbstractBase
    {
        private readonly string _secretText;

        public CustomCheckConditionalFormat(string secretText)
        {
            _secretText = secretText;
        }

        public CellFormat Check = new CellFormat()
        {
            Icon = "check",
            IconColor = "green",
        };

        public override CellFormat? CalculateFormat(int row, int col, Sheet sheet)
        {
            var cell = sheet.Cells.GetCell(row, col);
            var value = cell.GetValue<string>();

            if (value == null)
                return null;

            if (value.ToLower().Contains(_secretText))
                return Check;
            else
                return null;
        }
    }

}